<template>
  <div class="theme-switcher">
    <!-- 主题切换按钮 -->
    <el-dropdown trigger="click" @command="handleThemeChange">
      <el-button class="theme-toggle-btn">
        <el-icon><Brush /></el-icon>
        <span v-if="!isCollapsed">主题设置</span>
      </el-button>
      
      <template #dropdown>
        <el-dropdown-menu class="theme-dropdown">
          <el-dropdown-item 
            v-for="theme in availableThemes" 
            :key="theme.name"
            :command="theme.name"
            :class="{ 'active': currentTheme === theme.name && !isCustomTheme() }"
          >
            <div class="theme-item">
              <div class="theme-preview" :style="{ background: theme.primaryColor }"></div>
              <span class="theme-label">{{ theme.label }}</span>
              <el-icon v-if="currentTheme === theme.name && !isCustomTheme()" class="check-icon"><Check /></el-icon>
            </div>
          </el-dropdown-item>
          
          <el-dropdown-item divided>
            <div class="theme-custom">
              <span>自定义主题色</span>
              <el-color-picker 
                v-model="customColor" 
                :predefine="predefineColors"
                @change="handleCustomColorChange"
                size="small"
                show-alpha
                :teleported="false"
                :popper-options="{
                  modifiers: [
                    {
                      name: 'computeStyles',
                      options: {
                        gpuAcceleration: false
                      }
                    },
                    {
                      name: 'offset',
                      options: {
                        offset: [0, 8]
                      }
                    }
                  ]
                }"
              />
            </div>
          </el-dropdown-item>
          
          <el-dropdown-item divided>
            <div class="theme-presets">
              <span>预设颜色</span>
              <div class="color-swatches">
                <div 
                  v-for="color in presetColors" 
                  :key="color"
                  class="color-swatch"
                  :class="{ 'active': isCustomTheme() && customColor === color }"
                  :style="{ backgroundColor: color }"
                  @click="handlePresetColorClick(color)"
                ></div>
              </div>
            </div>
          </el-dropdown-item>
          
          <el-dropdown-item v-if="isCustomTheme()" divided>
            <div class="theme-reset">
              <el-button 
                type="text" 
                size="small"
                @click="handleResetTheme"
              >
                重置为默认主题
              </el-button>
            </div>
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!-- 快速切换按钮 -->
    <el-tooltip content="切换明暗主题" placement="bottom">
      <el-button 
        class="quick-toggle-btn" 
        :icon="isDarkMode ? Sunny : Moon"
        @click="toggleDarkMode"
      />
    </el-tooltip>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { Brush, Check, Moon, Sunny } from '@element-plus/icons-vue'
import { useThemeDSL, THEME_PRESETS, COLOR_PRESETS } from '../utils/themeDSL'

// Props
interface Props {
  isCollapsed?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  isCollapsed: false
})

// 主题管理
const { 
  getVariable, 
  setVariable, 
  setVariables, 
  applyPreset,
  applyColorTheme,
  setMode,
  toggleMode,
  getCurrentMode,
  getCurrentColorTheme,
  addListener
} = useThemeDSL()

// 计算属性
const currentTheme = computed(() => {
  // 使用新的方法获取当前颜色主题
  const colorTheme = getCurrentColorTheme()
  return colorTheme === 'default' ? 'custom' : colorTheme
})

const isDarkMode = computed(() => getCurrentMode() === 'dark')

const isCustomTheme = () => {
  return currentTheme.value === 'custom'
}

// 自定义颜色
const customColor = ref('#ff6b6b')

// 可用主题列表 - 只显示颜色主题，不包含模式主题
const availableThemes = computed(() => {
  return Object.entries(COLOR_PRESETS).map(([name, config]) => ({
    name,
    label: getPresetLabel(name),
    primaryColor: config['--primary-color'] || '#409eff',
    accentColor: config['--accent-color'] || '#79bbff'
  }))
})

const getPresetLabel = (name: string) => {
  const labels: Record<string, string> = {
    ins: 'INS风格',
    dopamine: '多巴胺配色'
  }
  return labels[name] || name
}

// 预设颜色 - 丰富的RGB色彩调色板
const presetColors = [
  // 暖色调
  '#ff6b6b', '#ff8e8e', '#ff6b9d', '#ff4757', '#ff3838',
  // 冷色调  
  '#3742fa', '#2f3542', '#5352ed', '#2ed573', '#1e90ff',
  // 中性色
  '#2c2c2c', '#666666', '#999999', '#b3b3b3', '#cccccc',
  // 活力色
  '#ffa502', '#ff6348', '#ff9ff3', '#54a0ff', '#5f27cd'
]

// 预定义颜色（用于颜色选择器）- 丰富RGB色彩方案
const predefineColors = [
  // 主色调系列
  '#ff6b6b',  // 珊瑚红
  '#ff6b9d',  // 粉紫
  '#3742fa',  // 蓝紫
  '#2ed573',  // 翠绿
  '#ffa502',  // 橙黄
  // 辅助色系列
  '#ff4757',  // 鲜红
  '#5352ed',  // 靛蓝
  '#1e90ff',  // 天蓝
  '#ff6348',  // 番茄红
  '#5f27cd'   // 深紫
]

// 处理主题切换
const handleThemeChange = (themeName: string) => {
  // 使用新的颜色主题方法
  applyColorTheme(themeName)
}

// 处理自定义颜色变化
const handleCustomColorChange = (color: string) => {
  if (color) {
    customColor.value = color
    setVariable('--primary-color', color)
    setVariable('--el-color-primary', color)
  }
}

// 处理预设颜色点击
const handlePresetColorClick = (color: string) => {
  customColor.value = color
  setVariable('--primary-color', color)
  setVariable('--el-color-primary', color)
}

// 处理重置主题
const handleResetTheme = () => {
  setVariables({
    '--primary-color': '#ff6b6b',
    '--accent-color': '#ff8e8e',
    '--el-color-primary': '#ff6b6b'
  })
  customColor.value = '#ff6b6b'
}

// 切换明暗主题
const toggleDarkMode = () => {
  // 使用新的切换模式方法
  toggleMode()
  
  // 确保Element Plus暗色主题正确应用
  const newMode = getCurrentMode()
  if (typeof document !== 'undefined') {
    if (newMode === 'dark') {
      document.documentElement.classList.add('dark')
    } else {
      document.documentElement.classList.remove('dark')
    }
  }
}

// 监听主题变化
watch(() => currentTheme.value, (newTheme) => {
  // 如果不是自定义主题，更新customColor以匹配当前主题
  if (!isCustomTheme()) {
    const theme = availableThemes.value.find(t => t.name === newTheme)
    if (theme) {
      customColor.value = theme.primaryColor
    }
  }
}, { immediate: true })

// 监听DSL变化
addListener((dsl) => {
  customColor.value = dsl['--primary-color'] || '#ff6b6b'
})
</script>

<style scoped>
.theme-switcher {
  display: flex;
  align-items: center;
  gap: 8px;
}

.theme-toggle-btn,
.quick-toggle-btn {
  background: transparent;
  border: none;
  padding: 8px;
  font-size: 16px;
  color: var(--text-color);
  cursor: pointer;
  transition: all var(--transition-fast);
  border-radius: 8px;
}

.theme-toggle-btn:hover,
.quick-toggle-btn:hover {
  color: var(--primary-color);
  background-color: rgba(106, 44, 112, 0.05);
}

.theme-dropdown {
  min-width: 200px;
}

.theme-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
}

.theme-preview {
  width: 20px;
  height: 20px;
  border-radius: 4px;
  border: 2px solid transparent;
}

.theme-label {
  flex: 1;
  font-size: 14px;
}

.check-icon {
  color: var(--primary-color);
  font-size: 16px;
}

.theme-custom {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 0;
}

/* 主题下拉菜单样式 - 使用CSS变量 */
:deep(.el-dropdown-menu) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
  box-shadow: var(--shadow-md) !important;
}

:deep(.el-dropdown-menu__item) {
  color: var(--text-color) !important;
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: var(--el-fill-color-light) !important;
  color: var(--text-color) !important;
}

:deep(.el-dropdown-menu__item.active) {
  background-color: var(--el-menu-active-bg-color) !important;
  color: var(--primary-color) !important;
}

/* 颜色选择器触发器样式 */
:deep(.el-color-picker__trigger) {
  cursor: pointer;
  box-shadow: none;
  border: 1px solid var(--border-color);
  transition: all var(--transition-fast);
}

:deep(.el-color-picker__trigger:hover) {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(255, 107, 107, 0.1);
}

/* 颜色选择器面板样式 */
:deep(.el-color-picker__panel) {
  z-index: 9999 !important;
  background-color: var(--card-background-color) !important;
  border: 1px solid var(--border-color) !important;
  box-shadow: var(--shadow-lg) !important;
  border-radius: 8px !important;
}

/* 颜色选择器下拉面板样式 */
:deep(.el-color-dropdown__main-wrapper) {
  background-color: var(--card-background-color) !important;
  border: 1px solid var(--border-color) !important;
  box-shadow: var(--shadow-lg) !important;
  border-radius: 8px !important;
}

/* 颜色选择器按钮样式 */
:deep(.el-color-dropdown__btn) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
  color: var(--text-color) !important;
  transition: all var(--transition-fast);
}

:deep(.el-color-dropdown__btn:hover) {
  background-color: var(--el-fill-color-light) !important;
  color: var(--text-color) !important;
  border-color: var(--primary-color) !important;
}

/* 颜色选择器输入框样式 */
:deep(.el-color-picker__input) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
  color: var(--text-color) !important;
  transition: all var(--transition-fast);
}

:deep(.el-color-picker__input:focus) {
  border-color: var(--primary-color) !important;
  box-shadow: 0 0 0 2px rgba(255, 107, 107, 0.1) !important;
}

/* 颜色选择器预设颜色区域 */
:deep(.el-color-predefine) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
}

:deep(.el-color-predefine__color-selector) {
  border-color: var(--border-color) !important;
  transition: all var(--transition-fast);
}

:deep(.el-color-predefine__color-selector:hover) {
  border-color: var(--primary-color) !important;
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 颜色选择器滑块和面板样式 */
:deep(.el-color-alpha-slider),
:deep(.el-color-hue-slider),
:deep(.el-color-svpanel) {
  background-color: var(--card-background-color) !important;
}

.theme-presets {
  padding: 8px 0;
}

.theme-presets span {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: var(--text-color);
}

.color-swatches {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 6px;
  max-height: 120px;
  overflow-y: auto;
}

.color-swatch {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  cursor: pointer;
  border: 2px solid transparent;
  transition: all var(--transition-fast);
  position: relative;
}

.color-swatch:hover {
  transform: scale(1.1);
  border-color: var(--primary-color);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 当预设颜色被选中时的样式 */
.color-swatch.active {
  border-color: var(--primary-color);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.color-swatch.active::after {
  content: "✓";
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #fff;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
  font-size: 14px;
}

.theme-reset {
  text-align: center;
  padding: 8px 0;
}

.theme-reset .el-button {
  color: var(--text-color-secondary);
  font-size: 12px;
}

.theme-reset .el-button:hover {
  color: var(--primary-color);
}

/* 活跃主题样式 */
:deep(.el-dropdown-menu__item.active) {
  background-color: rgba(106, 44, 112, 0.1);
  color: var(--primary-color);
}

:deep(.el-dropdown-menu__item:hover) {
  background-color: rgba(106, 44, 112, 0.05);
}

/* 强制覆盖颜色选择器弹出面板的样式 - 确保与主题一致 */
:deep(.el-popper.is-pure) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
  box-shadow: var(--shadow-md) !important;
}

:deep(.el-popper .el-color-picker__panel) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
}

:deep(.el-popper .el-color-dropdown__main-wrapper) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
}

/* 确保颜色选择器在深色模式下正确显示 */
.dark-theme :deep(.el-color-picker__panel) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
}

.dark-theme :deep(.el-color-dropdown__main-wrapper) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
}

.dark-theme :deep(.el-color-dropdown__btn) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
  color: var(--text-color) !important;
}

/* 确保颜色选择器在浅色模式下正确显示 */
.light-theme :deep(.el-color-picker__panel) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
}

.light-theme :deep(.el-color-dropdown__main-wrapper) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
}

.light-theme :deep(.el-color-dropdown__btn) {
  background-color: var(--card-background-color) !important;
  border-color: var(--border-color) !important;
  color: var(--text-color) !important;
}
</style> 